package com.sangmo.boot.auth.core.handlers;

import com.sangmo.boot.auth.core.AccessTokenService;
import com.sangmo.boot.auth.core.interfaces.GrantTokenRequest;
import com.sangmo.boot.auth.core.interfaces.GrantTokenResponse;
import com.sangmo.boot.auth.core.interfaces.ValidateTokenRequest;
import com.sangmo.boot.auth.core.model.AccessToken;
import com.sangmo.boot.auth.core.model.Client;
import com.sangmo.boot.framework.common.session.UserSession;
import org.springframework.beans.factory.annotation.Autowired;

public abstract class BaseAuthorizeHandler implements AuthorizeHandler {

	@Autowired
	protected  AuthorizeHelper authorizeHelper;
	@Autowired
	protected AccessTokenService tokenService;

	protected abstract AccessToken createToken(Client client, GrantTokenRequest req);

	protected abstract UserSession.Authorize<?> authorize(Client client, AccessToken accessToken);

	@Override
	public GrantTokenResponse grant(GrantTokenRequest req) {
		Client client = authorizeHelper.validateClientGrant(req.getClientId(), req.getSecret(), req.getGrantType(), req.getResource(), req.getScope());
		AccessToken token = createToken(client, req);
		GrantTokenResponse result = new GrantTokenResponse();
		result.setAccessToken(token.getValue());
		if (token.getValidity() == -1) {
			result.setExpiry(-1);
		}
		else {
			result.setExpiry(token.getLeftValidity());
		}
		return result;
	}
	
	@Override
	public UserSession.Authorize<?> validate(ValidateTokenRequest req) {
		AccessToken accessToken = tokenService.validateToken(req.getClientId(), req.getAccessToken());
		Client client = authorizeHelper.validateClientAccess(req.getClientId(), accessToken.getResource(), accessToken.getScope());

		UserSession.Authorize auth = authorize(client, accessToken);
		auth.setClientId(accessToken.getClientId());
		auth.setScope(accessToken.getScope());
		auth.setResource(accessToken.getResource());
		return auth;
	}
}
